package com.hundsun.yr.universal.p2p.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.adapter.HolderAdapter;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSLabelTextView;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView;
import com.hundsun.yr.universal.library.widget.HSSwipeRefreshLayout;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.bean.InvestEntity;
import com.hundsun.yr.universal.p2p.bean.ProductBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.ApiConstants2;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.BaseListEntityPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.BindCardActivity;
import com.hundsun.yr.universal.p2p.ui.activity.InvestActivity;
import com.hundsun.yr.universal.p2p.ui.activity.InvestDetailsActivity;
import com.hundsun.yr.universal.p2p.ui.activity.LoginActivity;
import com.hundsun.yr.universal.p2p.ui.activity.MainActivity;
import com.hundsun.yr.universal.p2p.ui.activity.OpenAccountBankActivity;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseFragment;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.BaseListView;
import com.hundsun.yr.universal.p2p.widget.RoundProgressBarWidthNumber;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by xx on 2017/8/9.
 */

public class AllProductFragment extends BaseFragment implements BaseListView, ViewCreatorHelper.UpdateItem<ProductBeen>
        , SwipeRefreshLayout.OnRefreshListener, HSLoadMoreListView.OnLoadMoreListener, AdapterView.OnItemClickListener {
    private RequestPresenter mPresenter;
    private HSSwipeRefreshLayout all_hsSwipeRefreshLayout;
    private HSLoadMoreListView all_loadMoreListView;
    private String zwgt_data;
    private HolderAdapter<ProductBeen> mAdapter;
    private String type;

    /**
     * product数据集合
     **/
    private List<ProductBeen> data = new ArrayList<ProductBeen>();
    private LayoutInflater mInflater;
    private RelativeLayout headerView;
    private int lastVisiblePosition;
    private Long time;
    private boolean isRefresh = false;

    public static final AllProductFragment newInstance(String type) {
        AllProductFragment fragment = new AllProductFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        fragment.setArguments(bundle);
        return fragment ;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.frag_all_product;
    }

    @Override
    protected void initViewsAndEvents() {
        type=getArguments().getString("type");

        findView();

        /**设置viewpager或者listView时候的一个帮组类**/
        ViewCreatorHelper<ProductBeen> creatorHelper = new ViewCreatorHelper<ProductBeen>(R.layout.item_invest_scattrered, this);
        mAdapter = new HolderAdapter<ProductBeen>(mContext, creatorHelper.viewCreator());

        //将头添加进去
        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        headerView = (RelativeLayout) mInflater.inflate(R.layout.item_header_10dp, all_loadMoreListView, false);
        all_loadMoreListView.addHeaderView(headerView);
        all_loadMoreListView.setAdapter(mAdapter);
        all_loadMoreListView.setOnItemClickListener(this);
        all_hsSwipeRefreshLayout.setOnRefreshListener(this);
        all_loadMoreListView.setOnLoadMoreListener(this);

        mPresenter = new BaseListEntityPresenterImpl(mContext, this, InvestEntity.BASEKEY);
        loadingdata();
        isRefresh = false;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void findView() {
        all_hsSwipeRefreshLayout = findView(R.id.all_hsSwipeRefreshLayout);
        all_loadMoreListView = findView(R.id.all_loadMoreListView);
    }

    @Override
    protected void onFirstUserVisible() {

    }

    /**
     * 加载网络数据
     */
    private void loadingdata() {
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        if (sharedPreferences.getBoolean(UserInfo.ISLOGIN)) {
            mPresenter.loadingData(TaskConstants.TASK_GOODSLIST, getString(R.string.root_url_test) + getString(R.string.api_index_test) + TaskConstants.TASK_GOODSLIST + "?type=" + type, Constants.EVENT_REFRESH_DATA, ApiConstants2.goodsChoicest("0"),
                    BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.api_index_test) + TaskConstants.TASK_GOODSLIST + "?type=" + type
                            , sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
        } else {
            mPresenter.loadingData(TaskConstants.TASK_GOODSLIST, getString(R.string.root_url_test) + getString(R.string.api_index_test) + TaskConstants.TASK_GOODSLIST + "?type=" + type, Constants.EVENT_REFRESH_DATA, ApiConstants2.goodsChoicest("0"),
                    BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.api_index_test) + TaskConstants.TASK_GOODSLIST + "?type=" + type
                            , sharedPreferences.getShareProf(UserInfo.USER_NO), ((MainActivity) getActivity()).mConfigSP.getShareProf(TaskConstants.TASK_CONFIG), zwgt_data), true);
        }
    }

    @Override
    protected void onUserVisible() {

    }

    @Override
    protected void onUserInvisible() {

    }

    @Override
    protected View getLoadingTargetView() {
        if (all_hsSwipeRefreshLayout == null) {
            all_hsSwipeRefreshLayout = findView(R.id.all_hsSwipeRefreshLayout);
        }
        return all_hsSwipeRefreshLayout;
    }

    @Override
    protected void onEveComming(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case Extras.SYSTEM_TIME_REFRESH:
                if (mAdapter != null) mAdapter.update(data);
                break;
        }
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    public <T> void refreshListData(List<T> result) {
        // TODO Auto-generated method stub
        all_hsSwipeRefreshLayout.setRefreshing(false);
        all_loadMoreListView.setLoadMoreEnabled(true);
        if (data.size() > 0) data.clear();
        if (result != null) {
            data.addAll((Collection<? extends ProductBeen>) result);
//			loadMoreListView.setLoadMoreEnabled(result.size()==Constants.PAGESIZE_MIDDLE);
            all_loadMoreListView.setLoadMoreEnabled(true);
        }
        mAdapter.update(data);
    }

    @Override
    public <T> void addMoreListData(List<T> result) {
        // TODO Auto-generated method stub
        all_loadMoreListView.onLoadMoreComplete();

        if (result != null && result.size() > 0) {
//			pageNo++;
            data.addAll((Collection<? extends ProductBeen>) result);
            all_loadMoreListView.setLoadMoreEnabled(true);
//			loadMoreListView.setLoadMoreEnabled(result.size()==Constants.PAGESIZE_MIDDLE);
        } else {
            all_loadMoreListView.setLoadMoreEnabled(false);
        }
        mAdapter.update(data);
    }

    @Override
    public <T> void onFailure(String task_name) {
        all_hsSwipeRefreshLayout.setRefreshing(false);
        if (TextUtils.equals(TaskConstants.TASK_GOODSLIST, task_name)) {

        } else if (TextUtils.equals(TaskConstants.TASK_GOODSLIST + "outTime",task_name) && isRefresh){
            sharedPreferences.putBoolean(UserInfo.ISLOGIN, false);
            CommTool.goToLogin(mContext);
            EventBus.getDefault().post(new EventCenter(Constants.EVENT_DATA_LOGIN_EXPIRED));
        }
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {

    }

    /**
     * 刷新时候的回掉
     */
    @Override
    public void onRefresh() {
        loadingdata();
        isRefresh = true;
    }

    /**
     * 更新数据
     *
     * @param view
     * @param position
     */
    @Override
    public void refreshItem(View view, final int position, ProductBeen entity) {
        /**
         * 进度代码	   含义	    对应恒生系统代码
         0	          未发布    0：未发布
         10			  投标中	1：投标中
         15			  待放款	无
         18			  放款中	无
         20			  计息中	2：计息中
         30			  待返还（暂时不用）	3：待返还
         40			  已返还	4：已返还
         50			  已结束	5：已结束
         60			  已撤销	6：已结束
         100		  逾期未返还
         105		  逾期部分返还（暂不开发）
         110		  逾期已返还
         120		  流标
         125		  停售（募集期截止但未募满）
         130		  风控拒绝放款
         200		  逾期已返还(与11重复废弃)
         */
        //将参数填写到对应的地方
        /**项目名称**/
        TextView tv_product_item_title = findView(view, R.id.tv_product_item_title);
        if (entity.name != null) {
            tv_product_item_title.setText(entity.name);
        }

        /**投资期限**/
        TextView tv_product_item_term = findView(view, R.id.tv_product_item_term);
        if (entity.pay_method != null) {
            tv_product_item_term.setText(entity.getTerm());
        }

        /**基础年化利率**/
        TextView tv_product_item_invest_rate = findView(view, R.id.tv_product_item_invest_rate);
        /**加息年利率标签**/
        HSLabelTextView hstv_raise_interest_rate = findView(view,R.id.hstv_raise_interest_rate);

        TextView add = findView(view, R.id.add);
        /**加息年化利率**/
        TextView tv_product_item_add_debt_rate = findView(view, R.id.tv_product_item_add_debt_rate);


        /**活动标签**/
        HSLabelTextView hstv_raise_interest_event = findView(view, R.id.hstv_raise_interest_event);
        if (entity.add_debt_rate != null) {
            if (MathUtils.compare(entity.add_debt_rate,"0") <= 0){
                add.setVisibility(View.GONE);
                tv_product_item_add_debt_rate.setVisibility(View.GONE);
                hstv_raise_interest_rate.setVisibility(View.GONE);
                if (entity.invest_rate != null) {
                    tv_product_item_invest_rate.setText(CommTool.formart2(Double.valueOf(entity.invest_rate)));
                }
            } else {
                add.setVisibility(View.VISIBLE);
                tv_product_item_add_debt_rate.setVisibility(View.VISIBLE);
                hstv_raise_interest_rate.setVisibility(View.VISIBLE);
                if (entity.add_rate_msg!=null){
                    hstv_raise_interest_rate.setText( entity.add_rate_msg);
                }
                if (entity.basic_debt_rate != null) {
                    tv_product_item_invest_rate.setText(CommTool.formart2(Double.valueOf(entity.basic_debt_rate)));
                }
                tv_product_item_add_debt_rate.setText(CommTool.formart2(Double.valueOf(entity.add_debt_rate)));
            }
        }
        if (entity.short_desc!=null&&!entity.short_desc.isEmpty()){
            hstv_raise_interest_event.setVisibility(View.VISIBLE);
            hstv_raise_interest_event.setText(entity.short_desc);
        }else {
            hstv_raise_interest_event.setVisibility(View.GONE);
        }
        /**新人专享**/
        HSLabelTextView hstv_new_exclusive = findView(view,R.id.hstv_new_exclusive);
        if (TextUtils.equals(entity.recruit_flag,"1")){
            hstv_new_exclusive.setVisibility(View.VISIBLE);
        } else {
            hstv_new_exclusive.setVisibility(View.GONE);
        }

        ProgressBar hspb_home_pecent = findView(view, R.id.hspb_home_pecent);
        hspb_home_pecent.setProgress(Integer.parseInt(entity.getPercent()));

        TextView hspb_home_pecent_text = findView(view,R.id.hspb_home_pecent_text);
        hspb_home_pecent_text.setText(entity.getPercent()+"%");

        TextView tv_surplus_invest = findView(view,R.id.tv_surplus_invest);
        tv_surplus_invest.setText(getString(R.string._residualaamount,entity.displayChangeAmount()));
        /**
         * 精选标记
         */
        HSLabelTextView hstv_selected_product = findView(view,R.id.hstv_selected_product);
        if (entity.favor_flag != null && !entity.favor_flag.isEmpty()) {
            switch (entity.favor_flag) {
                case "0":
                    hstv_selected_product.setVisibility(View.GONE);
                    break;
                case "1":
                    hstv_selected_product.setVisibility(View.VISIBLE);
                    break;
            }
        }

        /**
         * 项目募集状态
         */
        ImageView iv_product_raise_status = findView(view,R.id.iv_product_raise_status);
        switch (entity.product_status){
            case 0://未开售
                iv_product_raise_status.setImageResource(R.drawable.tab_not_open);
                break;
            case 1://募集中
                iv_product_raise_status.setImageResource(R.drawable.tab_investing);
                break;
            case 2://已满标
                iv_product_raise_status.setImageResource(R.drawable.tab_full_scale);
                break;
            case 3://已停售
                iv_product_raise_status.setImageResource(R.drawable.tab_complete);
                break;
            case 4://还款中
                iv_product_raise_status.setImageResource(R.drawable.tab_repaymenting);
                break;
            case 5://已还款
                iv_product_raise_status.setImageResource(R.drawable.tab_already_repaid);
                break;
            case 6://计息中
                iv_product_raise_status.setImageResource(R.drawable.tab_interest_accrualing);
                break;
        }
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        lastVisiblePosition = all_loadMoreListView.getLastVisiblePosition();
        time = Long.valueOf(data.get(lastVisiblePosition - 2).ctime);
        //加载更多的时候，拿到最后一条的信息
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        if (sharedPreferences.getBoolean(UserInfo.ISLOGIN)) {
            mPresenter.loadingData(TaskConstants.TASK_GOODSLIST, getString(R.string.root_url_test) + getString(R.string.api_index_test) + TaskConstants.TASK_GOODSLIST +
                    "?ctime=" + time + "&type=" + type, Constants.EVENT_LOAD_MORE_DATA, ApiConstants2.goodsChoicest("0"), BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.
                    string.api_index_test) + TaskConstants.TASK_GOODSLIST + "?ctime=" + time + "&type=" + type, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);

        } else {
            mPresenter.loadingData(TaskConstants.TASK_GOODSLIST, getString(R.string.root_url_test) + getString(R.string.api_index_test) + TaskConstants.TASK_GOODSLIST +
                    "?ctime=" + time + "&type=" + type, Constants.EVENT_LOAD_MORE_DATA, ApiConstants2.goodsChoicest("0"), BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.
                    string.api_index_test) + TaskConstants.TASK_GOODSLIST + "?ctime=" + time + "&type=" + type, "", ((MainActivity) getActivity()).mConfigSP.getShareProf(TaskConstants.TASK_CONFIG), zwgt_data), false);

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (isFastDoubleClick()){
            return;
        }

        // TODO Auto-generated method stub
        if (position > data.size() || position <= 0) return;
        if (!sharedPreferences.getBoolean(UserInfo.ISLOGIN)) {
            //如果没有登陆跳转到登陆页面
            Intent intent = new Intent(mContext, LoginActivity.class);
            mContext.startActivity(intent);
            showToast(R.string.tips_login);
            return;
        }

        //将id带过去用于网络请求，显示详情页面的信息
        Bundle bundle = new Bundle();
        bundle.putSerializable(Extras.DATA, data.get(position - 1));
        readyGo(InvestDetailsActivity.class, bundle);
    }

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }
}
